package cate.game.activity.customgrowth;

import cate.common.table.activity.customgrowth.CustomGrowthRow;
import cate.common.table.d.GDActivity;
import cate.common.table.d.GDFunc;
import cate.common.table.d.GDOperation;
import cate.common.table.item.hero.row.HeroBaseRow;
import cate.common.table.pay.PayItemRow;
import cate.common.util.GameResult;
import cate.game.activity.base.core.RoleActivitySingle;
import cate.game.activity.commonstarup.po.CommonStarUpGiftBag;
import cate.game.activity.customgrowth.msg.CustomGrowthInfoResp;
import cate.game.res.MixRes;
import cate.game.res.MixResAdder;
import cate.game.role.Role;
import cate.game.role.bag.hero.Hero;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;

import java.beans.Transient;
import java.util.*;

public class CustomGrowthActivity extends RoleActivitySingle {
    @NoteField("选中的英雄id")
    public int heroId;

    @NoteField("可选择的英雄列表英雄id")
    public Set<Integer> heroIds = new HashSet<>();

    @NoteField("礼包")
    public Map<Integer, CommonStarUpGiftBag> giftPackMap;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
        if (giftPackMap == null) {
            giftPackMap = new HashMap<>();
        }
        giftPackMap.values().forEach(item -> {
            item.initialize(role);
        });
        if (heroIds == null) {
            heroIds = new HashSet<>();
        }
    }

    @Override
    public void onEnter() {
        super.onEnter();
    }

    @Override
    public void onRoleOpen() {

    }

    @Override
    public void onRoleEnd() {
        heroId = 0;
        giftPackMap.clear();
        heroIds.clear();
    }

    @Override
    public void initSend() {
        noticeUpdate();
    }

    @Override
    public void excelCheck() {
        showAllHeroIds();
    }

    public void noticeUpdate() {
        role.sendNow(new CustomGrowthInfoResp(this));
    }

    /**
     * 选择定制英雄
     * @param heroId
     * @return
     */
    public GameResult<CustomGrowthActivity> chooseHero(int heroId) {
        GameResult<CustomGrowthActivity> r = new GameResult<>();
        r.data = this;
        if (heroId != 0 && !heroIds.contains(heroId)) {
            return r.fail("选择了不存在的英雄");
        }
        this.heroId = heroId;
        //显示定制礼包信息
        showGiftMap();
        return r;
    }

    /**
     * 选定英雄礼包内容
     */
    private void showGiftMap() {
        giftPackMap.clear();
        Map<Integer, CustomGrowthRow> chooseConfigs = showConfigs();
        for (CustomGrowthRow config : chooseConfigs.values()) {
            CommonStarUpGiftBag pack = new CommonStarUpGiftBag(config.heroId, false, false, 0);
            pack.initialize(role);
            giftPackMap.put(config.id, pack);
            HeroBaseRow row = role.getGame().table.hero.base.get(config.heroId);
            if (row == null) {
                continue;
            }
            //已拥有满足星级条件的选定英雄
            for (Hero hero : role.getBag().hero.getList()) {
                HeroBaseRow tpl = hero.getTpl(role.getGame());
                if (tpl != null) {
                    if (row.protoId == tpl.protoId && row.star <= tpl.star) {
                        //礼包开启
                        pack.enablePack();
                    }
                }
            }
        }
    }

    /**
     * 礼包列表
     * @return
     */
    private Map<Integer, CustomGrowthRow> showConfigs() {
        Map<Integer, CustomGrowthRow> retMap = new HashMap<>();
        switch (funcId()) {
            case GDFunc.CUSTOM_GROWTH: {
                for (CustomGrowthRow config : role.getGame().table.customGrowth.customGrowth.getList()) {
                    if (config.configId == configTid() && config.tid == heroId) {
                        retMap.put(config.id, config);
                    }
                }
            }
            break;
        }
        return retMap;
    }

    /**
     * 英雄列表
     */
    private void showAllHeroIds() {
        switch (funcId()) {
            case GDFunc.CUSTOM_GROWTH: {
                heroIds.clear();
                for (CustomGrowthRow config : role.getGame().table.customGrowth.customGrowth.getList()) {
                    if (config.configId == configTid()) {
                        heroIds.add(config.tid);
                    }
                }
                //原数据修改
                Map<Integer, CustomGrowthRow> allConfigs = showConfigs();
                if (allConfigs.isEmpty()) {
                    giftPackMap.clear();
                    return;
                }
                giftPackMap.entrySet().removeIf(kv -> !allConfigs.containsKey(kv.getKey()));
                if (giftPackMap.isEmpty() && heroId != 0) {
                    showGiftMap();
                }
            }
            break;
        }
    }

    @JsonIgnore
    @Transient
    private CustomGrowthRow getConfig(int tid) {
        switch (funcId()) {
            case GDFunc.CUSTOM_GROWTH:
                return role.getGame().table.customGrowth.customGrowth.get(tid);
        }
        return null;
    }

    @JsonIgnore
    @Transient
    private HeroBaseRow getBaseRow(int tid) {
        switch (funcId()) {
            case GDFunc.CUSTOM_GROWTH:
                return role.getGame().table.hero.base.get(tid);
        }
        return null;
    }

    /**
     * 英雄升星 礼包开启
     * @param uid
     */
    public void updateAvailable(String uid) {
        if (!enable()) {
            return;
        }
        Hero item = role.getBag().hero.getItem(uid);
        if (item == null) {
            return;
        }
        HeroBaseRow tpl = item.getTpl(role.getGame());
        if (tpl == null) {
            return;
        }
        CustomGrowthRow row = role.getGame().table.customGrowth.customGrowth.showHeroRow(item.tid, configTid());
        if (row == null) {
            return;
        }
        if (row.configId != configTid()) {
            return;
        }
        tryEnablePacks(tpl);
    }

    public void tryEnablePacks(HeroBaseRow tpl) {
        for (CommonStarUpGiftBag bag : giftPackMap.values()) {
            HeroBaseRow row = role.getGame().table.hero.base.get(bag.id);
            if (row == null) {
                continue;
            }
            if (row.protoId == tpl.protoId && row.star <= tpl.star) {
                bag.enablePack();
            }
        }
        noticeUpdate();
    }

    @Override
    public GameResult<Void> allowPay(PayItemRow pir) {
        GameResult<Void> r = new GameResult<>();
        int tid = pir.funcSubId;
        if (!giftPackMap.containsKey(tid)) {
            return r.fail("此奖励未激活");
        }
        CustomGrowthRow config = getConfig(tid);
        if (config == null) {
            return r.fail("未找到活动配置");
        }
        if (!giftPackMap.get(tid).available) {
            return r.fail("无购买资格");
        }
        HeroBaseRow baseRow = getBaseRow(config.heroId);
        if (baseRow == null) {
            return r.fail("未找到英雄基础配置");
        }
        if (config.limit != -1) {
            if (giftPackMap.get(tid).buyTimes >= config.limit) {
                return r.fail("限购次数不足");
            }
        }
        if (config.buyType != GDActivity.SHOP_TYPE_PAY) {
            return r.fail("不支持此购买模式");
        }
        MixRes rewardRes = new MixRes(config.reward);
        if (rewardRes.isEmpty()) {
            return r.fail("奖励为空");
        }
        return r.success();
    }

    @Override
    public void onPaySuccess(PayItemRow payItemRow) {
        CustomGrowthRow config = getConfig(payItemRow.funcSubId);
        if (config == null) {
            return;
        }
        MixRes reward = new MixRes(config.reward);
        EcResult exe = new MixResAdder().setRes(reward)
                .setOperation(GDOperation.CUSTOM_GROWTH)
                .setOperationSub(payItemRow.funcSubId)
                .setDialogReward(true)
                .setSendMailWhenFull(true)
                .exe(role);
        giftPackMap.get(payItemRow.funcSubId).addBuyTimes();
        noticeUpdate();
    }
}
